package cn.wolfcode.ssm.service.impl;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.domain.Notice;
import cn.wolfcode.ssm.mapper.NoticeMapper;
import cn.wolfcode.ssm.query.QueryObject;
import cn.wolfcode.ssm.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.api.scripting.ScriptUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        // 给发布人设置值
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();
        notice.setIssuer(employee);
        // 设置发布时间
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {

        // 删除通知时
        noticeMapper.deleteByPrimaryKey(id);
        // 同时删除中间表的通知数据
        noticeMapper.DeleteNoticeANDEmploye(id);
    }

    @Override
    public void update(Notice notice) {
        // 修改后重新设置发布时间
        notice.setPubdate(new Date());
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"pubdate desc"); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    // 用户查看通知消息的同时往中间表插入数据
    @Override
    public void SaveNoticeANDEmployee(Long nId, Long eId) {
        noticeMapper.SaveNoticeANDEmployee(nId,eId);
    }

    @Override
    public List<Long> selectEid(Long nId) {
        return noticeMapper.selectEid(nId);
    }

    @Override
    public List<Long> selectNid(Long eId) {
        return noticeMapper.selectNid(eId);
    }

    @Override
    public void updateStatus(Boolean status, Long id) {
        noticeMapper.updateStatus(status,id);
    }
}
